package com.gxuwz.com_property.login.controller;

import com.alibaba.fastjson.JSON;
import com.gxuwz.com_property.common.dto.ResponseDto;
import com.gxuwz.com_property.login.pojo.LoginUser;
import com.gxuwz.com_property.login.service.LoginService;
import com.gxuwz.com_property.user.pojo.User;
import com.gxuwz.com_property.utils.BCryptUtil;
import com.gxuwz.com_property.utils.JwtUtil;
import com.gxuwz.com_property.utils.MD5EncryptUtil;
import com.gxuwz.com_property.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    public LoginService loginService;
    /**
     * 测试
     * */
    @Autowired
    public LoginUser loginUser;

    /**
     * redis jwt 工具类注入
     * */
    @Autowired
    public JwtUtil jwtUtil;
    @Autowired
    public RedisUtil redisUtil;

    @Autowired
    private MD5EncryptUtil md5EncryptUtil;

    @Autowired
    public BCryptUtil bCryptUtil;


    /**
     * 登录
     * */
/*    @PostMapping("/api/login")
    private ResponseDto login(@RequestBody LoginUser loginUser){
        Map<String,Object> map = new HashMap<>();
        System.out.println("loginUser"+loginUser);

        String newMd5Pwd = md5EncryptUtil.encrypt(loginUser.getPassword());
        loginUser.setPassword(newMd5Pwd);

        LoginUser loginUser1 = loginService.loginUser(loginUser);

        if (loginUser1!=null){
            System.out.println("login loginUser setToken："+ loginUser1);

            Map<String,String> payload = new HashMap<>();
            String name = loginUser1.getName();
            String password  = loginUser1.getPassword();
            String role = loginUser1.getRole();

            String token = jwtUtil.generateToken(name,role);

            System.out.println("jwtUtil.generateToken(name):"+token);

            // 将令牌存储到 Redis
            *//*redisUtil.set(token, name, JwtUtil.EXPIRATION_TIME);*//*

 *//*           *
             * 由于没有设置VO类，所以将password置为空
             **//*
            loginUser1.setPassword("");
            loginUser1.setToken(token);

            return ResponseDto.success("登录成功",loginUser1);

        }else {
            return ResponseDto.error("登录失败",401);
        }

    }*/

    /**
     * 演示2BCrypt密码加密
     * */
    @PostMapping("/api/login")
    private ResponseDto BCryptlogin(@RequestBody LoginUser loginUser){
        Map<String,Object> map = new HashMap<>();
        System.out.println("loginUser"+loginUser);

        String captcha = loginUser.getCaptcha();

        // 检查 Redis 中是否存在该令牌
        /*boolean tokenExistsInRedis = redisUtil.hasKey(loginUser.getToken());*/

        // 验证码校验
        /*String captchaKey = "captcha:" + loginUser.getCaptchaKey();*/
/*        String captchaKey = "captcha:" + loginUser.getCaptchaKey();

        boolean captchaExistsInRedis = redisUtil.hasKey(captchaKey);
        if (!captchaExistsInRedis || !redisUtil.get(captchaKey).equals(captcha)) {
            return ResponseDto.error("验证码不正确", 401);
        }*/



        String account = loginUser.getAccount();
        String pwd = loginUser.getPassword();
        System.out.println("accountlogin:"+account);

        LoginUser loginUser1 = loginService.findloginUserByUserName(account);

        if (loginUser1!=null){
            System.out.println("login loginUser setToken："+ loginUser1);

            Map<String,String> payload = new HashMap<>();
            /**
             * 获取数据库查询出来的值，检查原始密码与加密后的密码是否匹配
             * */
            String name = loginUser1.getName();
            String password  = loginUser1.getPassword();

            /**
             * 检查原始密码与加密后的密码是否匹配
             *
             * @param rawPassword     用户输入的明文密码
             * @param encodedPassword 数据库中存储的加密密码
             * @return 如果匹配，则返回true，否则返回false*/

            boolean flag = bCryptUtil.checkPassword(pwd, password);
            System.out.println("flag:"+flag);

            if (flag){
                String role = loginUser1.getRole();
                //token 生成
                String token = jwtUtil.generateToken(name,role);

                System.out.println("jwtUtil.generateToken(name):"+token);

                // 将令牌存储到 Redis
                redisUtil.set(token, name, JwtUtil.EXPIRATION_TIME);

                /**
                 * 由于没有设置VO类，所以将password置为空
                 * */
                loginUser1.setPassword("");
                loginUser1.setToken(token);
                return ResponseDto.success("登录成功",loginUser1);

            }else {
                return ResponseDto.error("密码错误",401);
            }

        }else {
            return ResponseDto.error("该用户不存在",401);
        }

    }

/*    @PostMapping("/fastJson")
    private LoginUser fastJson(@PathParam("jsonStr") String jsonStr){


                *//*String jsonStr = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";*//*

                // 将 JSON 字符串反序列化为 Java 对象
                loginUser = JSON.parseObject(jsonStr, LoginUser.class);

        System.out.println("Deserialized loginUser: " + loginUser);

        return loginUser;
    }*/


    /**
     * 登出
     * */
    @GetMapping("/logout")
    private ResponseDto logout(HttpServletRequest request){
        // 从请求头中获取 Token
        String token = request.getHeader("Authorization");

        if (token != null && !token.isEmpty()) {
            // 从 Redis 中删除 Token 对应的缓存
            redisUtil.delete(token);
            // 返回成功信息
            return ResponseDto.success("登出成功");
        } else {
            // 如果 Token 不存在或为空，则返回错误信息
            return ResponseDto.error("无效的Token", 401);
        }
    }

    /**
     * 验证验证码
     *
     * reids进行存储，过期时间
     * */
    @GetMapping("/login/code")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response){

    }

}
